<?php
namespace Dealer\Model;
/**
 * ModelName
 */
class ProductModel extends BaseModel{

    protected $tableName = 'public_line';

    /**
     * 线路列表
     */
     public  function  lineList($where){
         $count      = $this->alias('l')
             ->where($where)->count();// 查询满足要求的总记录数
         //echo $this->_sql();die;
         $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
         $show       = $Page->show();// 分页显示输出

         // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
         $list=M('public_line as l')
             ->join('__AREAS__ as a on a.areaId=l.origin_id')
             ->join('LEFT JOIN __OPERATOR_LINE_SUPPLIER__ as s on s.supplier_id=l.add_user_id')
             ->field('l.supplier_id,l.adult_money,l.child_money,l.oldman_money,l.line_id,l.line_name,l.origin_id,l.line_sn,l.create_time,a.areaName,l.line_status,s.supplier_name')
             ->order('l.line_id desc')
             ->where($where)
             ->limit($Page->firstRow.','.$Page->listRows)
             ->select();

         return ['list'=>$list,'show'=>$show];
     }

     /**
      * 待审核线路总数
      */
     public  function  waitAudit($adminId){
         $count      = M('public_line')
             ->where(['supplier_id'=>$adminId,'line_status'=>0,'operator_id'=>0])->count();// 查询满足要求的总记录数
         return $count;
     }

     /**
      * 线路详情
      */
     public function  getLineDetail($where){
         $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');

         $field="a.areaName,s.supplier_name,l.*";
         $info=M('public_line as l')
             ->join('__AREAS__ as a on a.areaId=l.origin_id')
             ->join('LEFT JOIN __OPERATOR_LINE_SUPPLIER__ as s on s.supplier_id=l.supplier_id')
             ->field($field)
             ->where($where)
             ->find();

         //目的城市
         $destination=M('areas')->where(array('areaId'=>array('in',$info['destination_id'])))->select();
         $destinationCity=[];
         foreach ($destination as $k=>$v){
             $destinationCity[]=$v['areaName'];
         }
         $info['destinationCity']=implode(',',$destinationCity);


         //线路主题
         $theme=M('line_theme')->where(['theme_id'=>['in',$info['theme_id']]])->select();
         $themeName=[];
         foreach ($theme as $k=>$v){
             $themeName[]=$v['theme_name'];
         }
         $info['theme_name']='元';
         if($theme){
             $info['theme_name']=implode(',',$themeName);
         }

         //给运营商的特殊日期价格
         $info['specialPrice']=M('operator_special_price')->where(array('line_id'=>$info['line_id']))->select();

         $db_prefix=C('DB_PREFIX');
         //行程安排
         $trip=M('public_trip as t')
             ->where(['t.line_id'=>$where['l.line_id'],'supplier_id'=>$admin_id])
             ->field("t.* ")
             ->select();

         $model=M();
         foreach ($trip as $k=>$v){
             //当天景区
             if($v['scenic_spot']){
                 $sql="select CONCAT(s.scenic_name) as scenic_name  from {$db_prefix}public_single_scenic_price as p,{$db_prefix}public_single_scenic as s  where s.scenic_id=p.scenic_id and p.scenic_priceId in ({$v['scenic_spot']})";
                 $scenicName='';
                 $scenic=$model->query($sql);
                 foreach ($scenic as $vv){
                     $scenicName.=$vv['scenic_name'].',';
                 }
                 $trip[$k]['scenic_name']=trim($scenicName,',');
             }
             //当天酒店
             if($v['lodging']){
                 $sql="select CONCAT_WS('-',su.supplier_name,sr.room_name) as hotel_name from {$db_prefix}public_single_room_price as rp
                 left join {$db_prefix}public_single_room as sr on sr.room_id=rp.room_id
                 left join {$db_prefix}public_single_supplier as su on su.supplier_id=rp.supplier_id where rp.room_priceId in ({$v['lodging']})";
                 $hotelName='';
                 $hotel=$model->query($sql);
                 foreach ($hotel as $vv){
                     $hotelName.=$vv['hotel_name'].',';
                 }
                 $trip[$k]['hotel_name']=trim($hotelName,',');
             }
             //当天可升级酒店
             if($v['lodging']){
                 $sql="select CONCAT_WS('-',su1.supplier_name,sr1.room_name) as up_hotel_name from {$db_prefix}public_single_room_price as rp1
                left join {$db_prefix}public_single_room as sr1 on sr1.room_id=rp1.room_id
                left join {$db_prefix}public_single_supplier as su1 on su1.supplier_id=rp1.supplier_id where rp1.room_priceId in ( select room_price_id from {$db_prefix}line_upgrade_hotel where {$db_prefix}line_upgrade_hotel.up_hotel_id in( {$v['upgrade_lodging']}))
                  ";
                 $up_hotel_name='';
                 $up_hotel=$model->query($sql);
                 foreach ($up_hotel as $vv){
                     $up_hotel_name.=$vv['up_hotel_name'].',';
                 }
                 $trip[$k]['up_hotel_name']=trim($up_hotel_name,',');
             }

         }



         M('public_single_room_price as rp')
             ->join('__PUBLIC_SINGLE_ROOM__ as sr on sr.room_id=rp.room_id')
             ->join('LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as su on su.supplier_id=rp.supplier_id')
             ->field('sr.room_name,sr.star_level,rp.room_count,rp.room_priceId,rp.adult_actual_cost,rp.child_actual_cost,rp.money_type,su.supplier_name')
             ->where(array('rp.room_priceId'=>array('in',$info['room_price_id'])))
             ->select();


         foreach ($trip as $k=>$v){
             $trip[$k]['play']=M('public_play')->where(array('trip_id'=>$v['trip_id']))->select();
             $trip[$k]['shopping']=M('public_shopping')->where(array('trip_id'=>$v['trip_id']))->select();
         }
         $info['trip']=$trip;

         //签证信息
         $info['visa']='无';
         $visa=M('public_visa')->where(array('visa_id'=>$info['visa_id']))->find();
         if($visa){
             $info['visa']=$visa['visa_name'].'-'.$visa['visa_price'].'元';
         }


         $info['addition']=M('line_additional_product')->where(array('line_id'=>$info['line_id']))->select();

         //已选的基础服务,如酒店,交通,景区,保险
         $goTraffic=M('public_single_traffic_price as tp')
             ->join('left join __PUBLIC_SINGLE_TRAFFIC_SEAT__ as se on se.seat_id=tp.seat_id')
             ->join('left join __PUBLIC_SINGLE_TRAFFIC__ as tr on tr.traffic_id=tp.traffic_id')
             ->join('left join __PUBLIC_SINGLE_SUPPLIER__ as pu on pu.supplier_id=tp.supplier_id')
             ->field('tp.traffic_priceId,pu.supplier_name,tp.routes_name,tr.traffic_name,tp.adult_actual_cost,tp.child_actual_cost,tp.seat_num,se.seat_name,tp.money_type')
             ->where(array('tp.traffic_priceId'=>$info['go_price_id']))
             ->find();
         $info['goTraffic']=$goTraffic;
         //已选的回来交通方式
         $backTraffic=M('public_single_traffic_price as tp')
             ->join('left join __PUBLIC_SINGLE_TRAFFIC_SEAT__ as se on se.seat_id=tp.seat_id')
             ->join('left join __PUBLIC_SINGLE_TRAFFIC__ as tr on tr.traffic_id=tp.traffic_id')
             ->join('left join __PUBLIC_SINGLE_SUPPLIER__ as pu on pu.supplier_id=tp.supplier_id')
             ->field('tp.traffic_priceId,pu.supplier_name,tp.routes_name,tr.traffic_name,tp.adult_actual_cost,tp.child_actual_cost,tp.seat_num,se.seat_name,tp.money_type')
             ->where(array('tp.traffic_priceId'=>$info['back_price_id']))
             ->find();
         $info['backTraffic']=$backTraffic;
         //已选的酒店
         $checkedHotel=M('public_single_room_price as rp')
             ->join('__PUBLIC_SINGLE_ROOM__ as sr on sr.room_id=rp.room_id')
             ->join('LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as su on su.supplier_id=rp.supplier_id')
             ->field('sr.room_name,sr.star_level,rp.room_count,rp.room_priceId,rp.adult_actual_cost,rp.child_actual_cost,rp.money_type,su.supplier_name')
             ->where(array('rp.room_priceId'=>array('in',$info['room_price_id'])))
             ->select();
         $info['checkedHotel']=$checkedHotel;
         //已选景区
         $checkedScenic=M('public_single_scenic_price as rp')
             ->join('__PUBLIC_SINGLE_SCENIC__ as sr on sr.scenic_id=rp.scenic_id')
             ->join('LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as su on su.supplier_id=rp.supplier_id')
             ->field('sr.scenic_name,sr.scenic_level,rp.seat_num,rp.scenic_priceId,rp.adult_actual_cost,rp.child_actual_cost,rp.money_type,su.supplier_name')
             ->where(array('rp.scenic_priceId'=>array('in',$info['scenic_price_id'])))
             ->select();
         $info['checkedScenic']=$checkedScenic;

         //已选保险
         $checkedInsure=M('line_upgrade_insure as li')
             ->join('LEFT JOIN __PUBLIC_SINGLE_INSURE_PRICE__ as rp on rp.insure_priceId=li.insure_price_id')
             ->join('LEFT JOIN __PUBLIC_SINGLE_INSURE__ as sr on sr.insure_id=rp.insure_id')
             ->join('LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as su on su.supplier_id=rp.supplier_id')
             ->field('sr.insure_name,rp.seat_num,rp.insure_priceId,rp.adult_actual_cost,rp.child_actual_cost,rp.money_type,su.supplier_name,li.now_adult_price,li.now_child_price')
             ->where(array('li.line_id'=>$info['line_id']))
             ->select();

         $info['checkedInsure']=$checkedInsure;

         //已包含的升级服务
         $up_supplier_info=M('line_upgrade_hotel as lh')
             ->join('LEFT JOIN __PUBLIC_SINGLE_ROOM_PRICE__ as rp on rp.room_priceId=lh.room_price_id')
             ->join('LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as su on rp.supplier_id=su.supplier_id')
             ->join('LEFT JOIN __PUBLIC_SINGLE_ROOM__ as sr on sr.room_id=rp.room_id')
             ->where(array('lh.line_id'=>$info['line_id']))
             ->field('su.supplier_id,su.supplier_name,rp.money_type,rp.adult_actual_cost,rp.child_actual_cost,rp.star_level,rp.room_count,rp.user_count,sr.room_name,su.supplier_name,lh.to_reseller_price,lh.to_operator_price')
             ->select();

         $info['upgradeHotel']=$up_supplier_info;


         //可选和交通升级列表
         $upgradeTrafficList=M('line_upgrade_traffic')->where(array('line_id'=>$info['line_id']))->select();
         $info['upgradeTrafficList']=$upgradeTrafficList;

         //销售价格列表
         $priceList=M('public_price')->where(array('line_id'=>$info['line_id']))->select();
         $info['priceList']=$priceList;
         return $info;
     }


     /**
      * 线路下架
      */
     public  function  soldOut($id){
         $res=$this->where(['line_id'=>$id])->setField(['line_status'=>-1]);
         if($res!==false){
             return true;
         }
         return false;
     }

     /**
      * 线路表信息
      */
     public  function  lineSimpleInfo($id){
         return $this->where(['line_id'=>$id])->find();
     }


     /**
      * 开通此供应商的运营商
      */
     public  function  supplierParentOperator($where){

         $admin_id=session('dealer_user.pid')==0?session('dealer_user.supplier_id'):session('dealer_user.pid');
         $admin_operator_id=M('operator_line_supplier')->where(array('supplier_id'=>$admin_id))->getField('operator_id');

         $lineId=I('id');
         if($where['operator_name']){
             $newWhere['operator_flag']=1;
             $newWhere['pid']=0;
             $newWhere['_string']=" operator_name  like '%{$where['operator_name']}%'  or operator_sn  like '%{$where['operator_name']}%'";
             $res=M('operator as o')
                 ->field('o.*,lo.partner_status')
                 ->join("LEFT JOIN __LINE_OPERATOR__ as lo on lo.operator_id=o.operator_id and  lo.line_id={$lineId}")
                 ->where($newWhere)->select();
         }else{
             $res=M('operator as o')
                 ->field('o.*,lo.partner_status')
                 ->join("LEFT JOIN __LINE_OPERATOR__ as lo on lo.operator_id=o.operator_id and  lo.line_id={$lineId}")
                 ->where(array('o.operator_id'=>$admin_operator_id))->select();
         }
         return $res;
     }

     /**
      * 申请合作
      */
     public  function  applyLinePartner($data){
        if(!is_numeric($data['id'])||!is_numeric($data['oid'])){
            return ['msg'=>'非法数据请求!','status'=>-1];
        }

        $exists=M('line_operator')->where(['operator_id'=>$data['oid'],'line_id'=>$data['id']])->find();
        if($exists){
            return ['msg'=>'已经申请过!请勿重复申请','status'=>-1];
        }

        $addData['operator_id']=$data['oid'];
        $addData['line_id']=$data['id'];
        $addData['create_time']=time();
        $addData['partner_status']=0;
        $res=M('line_operator')->add($addData);
        if($res){
            return ['msg'=>'申请成功!请耐心等待运营商处理','status'=>-1];
        }
         return ['msg'=>'操作失败!','status'=>-1];
     }


     /**
      * 合作中的运营商列表
      */
     public  function  partnerLineOperator($lineId){
         $count      = M('line_operator as l')
                        ->where(array('l.line_id'=>$lineId))->count();// 查询满足要求的总记录数
         $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
         $show       = $Page->show();// 分页显示输出

         // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
         //所有合作线路列表
         $list=M('line_operator as l')
             ->join("__OPERATOR__ as o on l.operator_id=o.operator_id")
             ->where(array('l.line_id'=>$lineId))
             ->field('l.*,o.operator_name')
             ->limit($Page->firstRow.','.$Page->listRows)
             ->select();
         return ['list'=>$list,'show'=>$show];

     }

     /**
      * 团列表
      */
     public  function  groupList($where){

         $countList      = M('public_group as g')
             ->join("LEFT JOIN __LINE_ORDERS__ as o on o.group_id=g.group_id")
             ->join("__PUBLIC_LINE__ as pl on pl.line_id=g.line_id")
             ->join('__OPERATOR__ as op on op.operator_id=pl.operator_id')
             ->group('g.group_id')
             ->field('g.group_id')
             ->where($where)
             ->select();// 查询满足要求的总记录数
         $count=count($countList);
         $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
         $show       = $Page->show();// 分页显示输出

         // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
         $field="g.*,pl.line_name,pl.line_sn,op.operator_name";
         $list=M('public_group as g')
             ->join("LEFT JOIN __LINE_ORDERS__ as o on o.group_id=g.group_id")
             ->join("__PUBLIC_LINE__ as pl on pl.line_id=g.line_id")
             ->join('__OPERATOR__ as op on op.operator_id=pl.operator_id')
             ->field($field)
             ->where($where)
             ->order('g.group_id desc')
             ->group('g.group_id')
             ->limit($Page->firstRow.','.$Page->listRows)
             ->select();

         return ['list'=>$list,'show'=>$show];
     }

     /**
      * 导出团列表
      */
     public  function exportExcelGroupList($where){
         $field="g.*,pl.line_name,pl.line_sn,op.operator_name";
         $list=M('public_group as g')
             ->join("LEFT JOIN __LINE_ORDERS__ as o on o.group_id=g.group_id")
             ->join("__PUBLIC_LINE__ as pl on pl.line_id=g.line_id")
             ->join('__OPERATOR__ as op on op.operator_id=pl.operator_id')
             ->field($field)
             ->group('g.group_id')
             ->order('g.group_id desc')
             ->where($where)
             ->select();

         foreach ($list as $k=>$v){
             $list[$k]['group_time']=$v['group_time']?date("Y-m-d",$v['group_time']):'';
             $list[$k]['out_time']=date("Y-m-d",$v['out_time']);
             $list[$k]['received_num']=$v['expect_num']-$v['received_num'];
             $list[$k]['group_status']=self::groupStatus($v['group_status']);
         }

         $expCellName  = array(
             array('line_name','线路名称'),
             array('line_sn','线路编号'),
             array('group_num','团号'),
             array('group_time','成团时间'),
             array('out_time','出团时间'),
             array('received_num','余位'),
             array('expect_num','预计收客'),
             array('operator_name','商户信息'),
             array('group_status','成团状态')
         );

         $fileName=$list[0]['operator_name'].'团列表';
         parent::exportExcel($fileName,$expCellName,$list);
     }
     /**
      * 成团状态
      */
     public  function groupStatus($status){
         $result='';
         switch ($status){
             case 0: $result='待处理';break;
             case -1: $result='不成团';break;
             case 1: $result='已成团';break;
             case 2: $result='待出团';break;
             case 3: $result='已回团';break;
         }
         return $result;
     }
     /**
      * 订单状态
      */
     public  function orderStatus($status){
         $result='';
         switch ($status){
             case -1: $result='未支付';break;
             case -2: $result='审核不通过';break;
             case -3: $result='退款审核中';break;
             case -4: $result='拒绝退款';break;
             case -5: $result='订单已退款';break;
             case -6: $result='订单取消';break;
             case 1: $result='待审核';break;
             case 2: $result='审核中';break;
             case 3: $result='已审核';break;
         }
         return $result;
     }


     /**
      * 团号详情
      */
     public  function  groupDetail($group_id){
            $groupInfo=M('public_group')->where(['group_id'=>$group_id])->find();

            //线路出发地
            $lineInfo=M('public_line')->where(['line_id'=>$groupInfo['line_id']])->find();
            $groupInfo['startAddr']=M('areas')->where(['areaId'=>$lineInfo['origin_id']])->getField('areaName');

            if($groupInfo['channel']==1){
                //门店
                $groupInfo['shop_name']=M('operator')->where(['operator_id'=>$groupInfo['shop_id']])->getField('operator_name');
            }else if($groupInfo['channel']==2){
                //销售
                $groupInfo['shop_name']=M('operator_line_reseller')->where(['reseller_id'=>$groupInfo['shop_id']])->getField('reseller_name');
            }


             $where['o.group_id']=$group_id;

             //已审核的订单
             //$where['o.order_status']=3;


            $count=M('line_orders as o')
             ->where($where)
             ->count();

            $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出


            $field="o.order_id,o.order_num,t.tourists_name,t.tourists_phone,l.line_name,l.line_sn,l.travel_days,o.adult_num,o.child_num,o.oldMan_num,o.order_status,o.operator_cost";
            $list=M('line_orders as o')
                ->join("LEFT JOIN __PUBLIC_TOURISTS__ as t on t.tourists_id=o.contact_id")
                ->join("LEFT JOIN __PUBLIC_LINE__ as l on l.line_id=o.line_id")
                ->field($field)
                ->where($where)
                ->limit($Page->firstRow.','.$Page->listRows)
                ->select();

         return ['list'=>$list,'show'=>$show,'group'=>$groupInfo];
     }


     /**
      * 导出团详情
      */
     public  function  exportExcelGroupDetail($group_id){
         $groupInfo=M('public_group')->where(['group_id'=>$group_id])->find();

         //线路出发地
         $lineInfo=M('public_line')->where(['line_id'=>$groupInfo['line_id']])->find();
         $groupInfo['startAddr']=M('areas')->where(['areaId'=>$lineInfo['origin_id']])->getField('areaName');

         if($groupInfo['channel']==1){
             //门店
             $groupInfo['shop_name']=M('operator')->where(['operator_id'=>$groupInfo['shop_id']])->getField('operator_name');
         }else if($groupInfo['channel']==2){
             //销售
             $groupInfo['shop_name']=M('operator_line_reseller')->where(['reseller_id'=>$groupInfo['shop_id']])->getField('reseller_name');
         }

         $where['o.group_id']=$group_id;

         //已审核的订单
         $where['o.order_status']=3;

         $field="o.order_status,o.order_id,o.order_num,t.tourists_name,t.tourists_phone,l.line_name,l.line_sn,l.travel_days,o.adult_num,o.child_num,o.oldMan_num,o.order_status,o.operator_cost";
         $list=M('line_orders as o')
             ->join("LEFT JOIN __PUBLIC_TOURISTS__ as t on t.tourists_id=o.contact_id")
             ->join("LEFT JOIN __PUBLIC_LINE__ as l on l.line_id=o.line_id")
             ->field($field)
             ->where($where)
             ->select();

         foreach ($list as $k=>$v ){
             $list[$k]['shopName']= $groupInfo['shop_name'];
             $list[$k]['startAddr']= $groupInfo['startAddr'];
             $list[$k]['people']="成:{$v['adult_num']};儿:{$v['child_num']}";
             $list[$k]['order_status']=self::orderStatus($v['order_status']);
         }



         $expCellName  = array(

             array('order_num','订单号'),
             array('tourists_name','游客姓名'),
             array('tourists_phone','联系方式'),
             array('line_name','线路名称'),
             array('line_sn','线路编号'),
             array('startAddr','出发地'),
             array('travel_days','行程天数'),
             array('people','人数'),
             //array('operator_cost','结算总金额'),
             array('order_status','状态'),
             array('shopName','商户信息'),
         );
         $fileName=$groupInfo['group_num'].'团列表';
         parent::exportExcel($fileName,$expCellName,$list);
     }

/**
 * 审核线路
 */
public  function  auditLine(){
    $id=I('id',0,'intval');
    $status=I('status',0,'intval');
    if(!$id||!$status){
        return false;
    }

    $res=M('public_line')->where(array('line_id'=>$id))->setField(array('line_status'=>$status));
    if($res){
        return true;
    }
    return false;
}












}

